<?php

namespace WeForge\Runtime;

use HttpClient\Aliyun\Factory;
use Illuminate\Support\Collection;
use Throwable;

class Secrets
{
    /**
     * The KMS instance.
     *
     * @var \HttpClient\Aliyun\KeyManagementService\Application
     */
    protected static $kms;

    /**
     * Add all of the secret parameters at the given path to the environment.
     *
     * @param string $path
     * @param string $variables
     *
     * @return void
     */
    public static function addToEnvironment($path, $variables)
    {
        $variables = static::all(
            $path, json_decode($variables, true)
        );

        $secrets = fopen('/tmp/.weforge/secrets', 'w');

        foreach ($variables as $key => $value) {
            fwrite($secrets, "export {$key}=$(cat <<EOF
{$value}
EOF
)".PHP_EOL
            );
        }

        fclose($secrets);
    }

    /**
     * Get all of the secret parameters at the given path.
     *
     * @param  string  $path
     * @param  array  $parameters
     * @return array
     */
    public static function all($path, array $parameters)
    {
        return Collection::make($parameters)->flatMap(function ($version, $parameter) use ($path) {
            try {
                return [
                    $parameter => static::kms()->secret->value($path.$parameter, $version)['SecretData'],
                ];
            } catch (Throwable $e) {
                //
            }
        })->all();
    }

    /**
     * Resolve the KMS instance.
     *
     * @return \HttpClient\Aliyun\KeyManagementService\Application
     */
    protected static function kms()
    {
        return static::$kms ?: static::$kms = Factory::keyManagementService([
            'http' => [
                'base_uri' => $_ENV['WEFORGE_KMS_ENDPOINT'],
            ],
            'access_key_id' => $_ENV['accessKeyID'] ?? $_ENV['ALIYUN_ACCESS_KEY_ID'] ?? null,
            'access_key_secret' => $_ENV['accessKeySecret'] ?? $_ENV['ALIYUN_SECRET_ACCESS_KEY'] ?? null,
            'security_token' => $_ENV['securityToken'] ?? null,
        ]);
    }
}
